/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-02-23 18:41:13
 * @LastEditTime: 2024-07-14 19:08:46
 * @FilePath: /nest_study/web/src/App.tsx
 */
import { BrowserRouter, useRoutes } from "react-router-dom";
import './styles/index.scss';
import { syncRouters } from "./router";
import { useEffect, useState } from "react";
import { initTheme } from "./styles/theme";
import { ConfigProvider, message } from "antd";
import zhCN from 'antd/es/locale/zh_CN';
import AuthRouter from "./components/auth_router";
import Spinner from "./components/spinner";
import { IRoute } from "./router/router.types";
import { useRootStore } from "./store";
import { dealRouteData, loadComponent } from "./router/deal";
import { observer } from "mobx-react-lite";
import { proxyToObject } from "./utils";
import { getCache, setCache } from "./utils/storage";
import { remoteUserAuth } from "./api/login";

function App() {

  const { user, settings, permissions } = useRootStore();
  const { loadingCount } = user;
  const { paveRoutes } = permissions;
  const [theme, setTheme] = useState<object>();
  //页面级加载初始化
  const [pageLoading, setPageLoading] = useState<boolean>(false)
  let [currentRoutes, setCurrentRoutes] = useState<Array<IRoute>>();
  //初始化
  useEffect(() => {
    setPageLoading(true);
    user.resetLoading();
    let token = getCache('token')
    if (token) {
      dynamicMenus()
    }
  }, [])

  //动态获取路由
  const dynamicMenus = async () => {
    let token = await getCache('token');
    if (token) {
      let authResult = await remoteUserAuth();
      if (authResult.data.length == 0) {
        message.error('无访问权限');
        user.setUserToken('');
        setCache('token', '');
        window.location.replace('/login');
        return false;
      }
      let result = dealRouteData(authResult.data);
      let { buttonPermissions, menuRouter, paveRouters, homeRoute } = result;
      permissions.init(buttonPermissions, menuRouter, paveRouters, homeRoute);
    }
    setPageLoading(false);
  }

  //主题切换
  useEffect(() => {
    const currentTheme = initTheme(settings.theme);
    setTheme(currentTheme);
  }, [settings.theme]);

  //处理动态路由
  useEffect(() => {
    let list = proxyToObject(paveRoutes);
    dealAsyncRoutes(list);
  }, [paveRoutes])

  //动态路由处理加载
  const dealAsyncRoutes = (routes: Array<IRoute>) => {
    routes.map((item: IRoute) => {
      return item.element = loadComponent(item.path, item.type)
    })
    setCurrentRoutes(routes);
    setPageLoading(false);
  }

  //项目路由处理集合
  const RouteElement = (props: { routes?: Array<IRoute> }) => {
    let getRoutes = syncRouters(props.routes);
    let element = useRoutes(getRoutes);
    return element;
  }

  return (
    <>
      {
        pageLoading ? <Spinner text="页面加载..." /> : (
          <ConfigProvider
            locale={zhCN}
            componentSize={'middle'}
            theme={{
              ...theme
            }}
          >
            <BrowserRouter>
              {
                loadingCount > 0 && <Spinner text="请求数据..." />
              }
              <AuthRouter>
                <RouteElement routes={currentRoutes} />
              </AuthRouter>
            </BrowserRouter>
          </ConfigProvider>
        )
      }
    </>
  );
}

export default observer(App);
